package com.bowen.spike.handler;


import com.bowen.spike.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 全局异常处理类
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    // 参数校验统一处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return ResponseEntity
                .status(HttpStatus.OK.value())
                .body(Result.error("请求参数"+objectError.getDefaultMessage()));
    }

    // 其他错误
    @ExceptionHandler(Exception.class)
    public ResponseEntity CustonExceptionHandler(Exception e) {
        return ResponseEntity
                .status(HttpStatus.OK.value())
                .body(Result.error(e.getMessage()));
    }


}
